{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Hashed Features Design Pattern\n",
    "\n",
    "Solves problems related to not knowing the vocabulary of a categorical variable beforehand."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "metadata": {},
   "outputs": [],
   "source": [
    "%%bigquery df\n",
    "CREATE TEMPORARY FUNCTION hashed(airport STRING, numbuckets INT64) AS (\n",
    "   ABS(MOD(FARM_FINGERPRINT(airport), numbuckets))\n",
    ");\n",
    "\n",
    "WITH airports AS (\n",
    "SELECT \n",
    "   DISTINCT(departure_airport)\n",
    "FROM `bigquery-samples.airline_ontime_data.flights`\n",
    ")\n",
    "\n",
    "SELECT \n",
    "   departure_airport,\n",
    "   hashed(departure_airport, 3) AS hash3,\n",
    "   hashed(departure_airport, 10) AS hash10,\n",
    "   hashed(departure_airport, 1000) AS hash1000,\n",
    "FROM airports"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>departure_airport</th>\n",
       "      <th>hash3</th>\n",
       "      <th>hash10</th>\n",
       "      <th>hash1000</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>SJU</td>\n",
       "      <td>2</td>\n",
       "      <td>1</td>\n",
       "      <td>81</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>PVD</td>\n",
       "      <td>1</td>\n",
       "      <td>7</td>\n",
       "      <td>667</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>MSY</td>\n",
       "      <td>1</td>\n",
       "      <td>1</td>\n",
       "      <td>991</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>MHT</td>\n",
       "      <td>2</td>\n",
       "      <td>7</td>\n",
       "      <td>507</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>CHS</td>\n",
       "      <td>1</td>\n",
       "      <td>2</td>\n",
       "      <td>432</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>5</th>\n",
       "      <td>CPR</td>\n",
       "      <td>2</td>\n",
       "      <td>6</td>\n",
       "      <td>306</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>6</th>\n",
       "      <td>PHX</td>\n",
       "      <td>0</td>\n",
       "      <td>3</td>\n",
       "      <td>743</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>7</th>\n",
       "      <td>SFO</td>\n",
       "      <td>0</td>\n",
       "      <td>4</td>\n",
       "      <td>714</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>8</th>\n",
       "      <td>SNA</td>\n",
       "      <td>2</td>\n",
       "      <td>7</td>\n",
       "      <td>587</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>9</th>\n",
       "      <td>SAN</td>\n",
       "      <td>0</td>\n",
       "      <td>7</td>\n",
       "      <td>447</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "  departure_airport  hash3  hash10  hash1000\n",
       "0               SJU      2       1        81\n",
       "1               PVD      1       7       667\n",
       "2               MSY      1       1       991\n",
       "3               MHT      2       7       507\n",
       "4               CHS      1       2       432\n",
       "5               CPR      2       6       306\n",
       "6               PHX      0       3       743\n",
       "7               SFO      0       4       714\n",
       "8               SNA      2       7       587\n",
       "9               SAN      0       7       447"
      ]
     },
     "execution_count": 23,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "df.head(n=10)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "347"
      ]
     },
     "execution_count": 24,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "len(df)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Some airports had very few flights"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>departure_airport</th>\n",
       "      <th>num_flights</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>MKC</td>\n",
       "      <td>1</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>BFF</td>\n",
       "      <td>1</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>PVU</td>\n",
       "      <td>1</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>GLH</td>\n",
       "      <td>2</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>FMN</td>\n",
       "      <td>3</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>5</th>\n",
       "      <td>PUB</td>\n",
       "      <td>4</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>6</th>\n",
       "      <td>OGD</td>\n",
       "      <td>5</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>7</th>\n",
       "      <td>CKB</td>\n",
       "      <td>8</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>8</th>\n",
       "      <td>PIR</td>\n",
       "      <td>14</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>9</th>\n",
       "      <td>SHD</td>\n",
       "      <td>18</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "  departure_airport  num_flights\n",
       "0               MKC            1\n",
       "1               BFF            1\n",
       "2               PVU            1\n",
       "3               GLH            2\n",
       "4               FMN            3\n",
       "5               PUB            4\n",
       "6               OGD            5\n",
       "7               CKB            8\n",
       "8               PIR           14\n",
       "9               SHD           18"
      ]
     },
     "execution_count": 27,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "%%bigquery\n",
    "SELECT \n",
    "   departure_airport, COUNT(1) AS num_flights\n",
    "FROM `bigquery-samples.airline_ontime_data.flights`\n",
    "GROUP BY departure_airport\n",
    "ORDER BY num_flights ASC\n",
    "LIMIT 10"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Likelihood of collision\n",
    "\n",
    "To calculate the likelihood of collision, consider that previous N entries don't collide.\n",
    "Even with 100,000 hash-length, the chance of a collision is 45%. So, hashed columns should never be used if collisions will cause problems."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 37,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>num_hash_buckets</th>\n",
       "      <th>entries_per_bucket</th>\n",
       "      <th>collision_prob</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>3</td>\n",
       "      <td>115.666667</td>\n",
       "      <td>1.000000</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>10</td>\n",
       "      <td>34.700000</td>\n",
       "      <td>1.000000</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>100</td>\n",
       "      <td>3.470000</td>\n",
       "      <td>1.000000</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>1000</td>\n",
       "      <td>0.347000</td>\n",
       "      <td>1.000000</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>10000</td>\n",
       "      <td>0.034700</td>\n",
       "      <td>0.997697</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>5</th>\n",
       "      <td>100000</td>\n",
       "      <td>0.003470</td>\n",
       "      <td>0.451739</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "   num_hash_buckets  entries_per_bucket  collision_prob\n",
       "0                 3          115.666667        1.000000\n",
       "1                10           34.700000        1.000000\n",
       "2               100            3.470000        1.000000\n",
       "3              1000            0.347000        1.000000\n",
       "4             10000            0.034700        0.997697\n",
       "5            100000            0.003470        0.451739"
      ]
     },
     "execution_count": 37,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import pandas as pd\n",
    "\n",
    "def calc_collision_prob(num_total, num_hash):\n",
    "    no_collision_prob = 1.0\n",
    "    for i in range(num_total):\n",
    "        # i of the previous buckets is occupied now\n",
    "        collision_likelihood = float(i) / num_hash\n",
    "        no_collision_prob *= (1 - collision_likelihood)\n",
    "    return 1 - no_collision_prob\n",
    "\n",
    "\n",
    "data = []\n",
    "for num_hash in [3, 10, 100, 1000, 10000, 100000]:\n",
    "    data.append([num_hash, \n",
    "                 len(df)/num_hash, \n",
    "                 calc_collision_prob(len(df), num_hash)\n",
    "                ])\n",
    "prob = pd.DataFrame(data, columns=['num_hash_buckets', 'entries_per_bucket', 'collision_prob'])\n",
    "prob"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 29,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0.009965049976000118"
      ]
     },
     "execution_count": 29,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "calc_collision_prob(5, 1000) # num_hash >> num_total"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Airports that share hash buckets\n",
    "\n",
    "Which airports have the same hashbucket as Chicago, assuming 100 hash buckets?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 33,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>departure_airport</th>\n",
       "      <th>num_flights</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>ORD</td>\n",
       "      <td>3610491</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>BTV</td>\n",
       "      <td>66555</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>MCI</td>\n",
       "      <td>597761</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "  departure_airport  num_flights\n",
       "0               ORD      3610491\n",
       "1               BTV        66555\n",
       "2               MCI       597761"
      ]
     },
     "execution_count": 33,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "%%bigquery\n",
    "CREATE TEMPORARY FUNCTION hashed(airport STRING, numbuckets INT64) AS (\n",
    "   ABS(MOD(FARM_FINGERPRINT(airport), numbuckets))\n",
    ");\n",
    "\n",
    "WITH airports AS (\n",
    "SELECT \n",
    "   departure_airport, COUNT(1) AS num_flights\n",
    "FROM `bigquery-samples.airline_ontime_data.flights`\n",
    "GROUP BY departure_airport \n",
    ")\n",
    "\n",
    "SELECT \n",
    "   departure_airport, num_flights\n",
    "FROM airports\n",
    "WHERE hashed(departure_airport, 100) = hashed('ORD', 100)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Copyright 2020 Google Inc. Licensed under the Apache License, Version 2.0 (the \"License\"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.5.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
